from layers.board import Board, CannotAddTileException, CoordinateOutOfBoundsException
from layers.soil.soilLayer import SoilGenerator
from objects.animals.animal import Animal
from tiles import tile

class GameBoard(Board):
#Combines multiple layers into one big board
    def __init__(self):
        super(GameBoard,self).__init__()
        self.soilLayer = SoilGenerator().generateLayer()
        self.groundLayer = Board()
        self.showVisionLayer = True
        self.entities = []
    
    def placeTile(self, x, y, tile):
    #adds a new instance of tile at coordinate x,y
        try:
            currentTile = self.getTile(x,y)
            self.groundLayer.placeTile(x,y,tile)
            #if tile.canBePlayedOn(currentTile):
            #self.coords[x][y] = tile.onPlacement()
            self.entities.append(tile)
            return True
            #else: raise CannotAddTileException, "%s cannot be played on %s at %s,%s" %(tile, currentTile,x,y)
        except CoordinateOutOfBoundsException: raise
    
    def getTile(self, x, y):
        try:
            return self.groundLayer.getTile(x,y)
        except CoordinateOutOfBoundsException: raise
    
    def getCreatures(self):
    #returns all the creatures on the board
        creatures = []
        for x in self.entities:
            if isinstance(x, Animal):
                creatures.append(x)
        return creatures
    
    def buildVisionLayer(self):
        visionLayer = Board(tile.InvisibleTile)
        creatures = self.getCreatures()
        if creatures:
            for creature in creatures:
                location = creature.location
                nodes = Board.getNodesInRadius(location[0], location[1], creature.vision)
                for node in nodes:
                    try:
                        visionLayer.placeTile(node[0], node[1], tile.VisibleTile())
                    except CoordinateOutOfBoundsException:
                        pass
        return visionLayer
                        
    def drawBoard(self):
        self.soilLayer.drawBoard()
        self.groundLayer.drawBoard()
        if self.showVisionLayer:
            visionLayer = self.buildVisionLayer()
            visionLayer.drawBoard()
            